package sit.engreal.leetcode.problems100;

import org.junit.jupiter.api.Assertions;

/**
 * <a herf="https://leetcode.cn/problems/zigzag-conversion/submissions/">6. Z 字形变换</a>
 */
public class LeetCode6 {
    public static class Solution {
        public String convert(String s, int numRows) {
            if (numRows == 1) {
                return s;
            }
            final StringBuilder[] v = new StringBuilder[numRows];
            for (int i = 0; i < v.length; i++) {
                v[i] = new StringBuilder();
            }
            int k = 0;
            OUT:
            for (; ; ) {
                for (StringBuilder builder : v) {
                    if (k >= s.length()) {
                        break OUT;
                    }
                    builder.append(s.charAt(k));
                    k++;
                }
                for (int i = v.length - 2; i > 0; i--) {
                    if (k >= s.length()) {
                        break OUT;
                    }
                    v[i].append(s.charAt(k));
                    k++;
                }
            }
            final StringBuilder result = new StringBuilder();
            for (StringBuilder builder : v) {
                result.append(builder);
            }
            return result.toString();

        }
    }

    public static void main(String[] args) {
        final Solution solution = new Solution();

        Assertions.assertEquals("PAHNAPLSIIGYIR", solution.convert("PAYPALISHIRING", 3));
        Assertions.assertEquals("PINALSIGYAHRPI", solution.convert("PAYPALISHIRING", 4));
    }
}
